import 'package:flutter/material.dart';
import '../../config/theme/theme_manager.dart';

/// 通用按钮组件
/// 提供统一的按钮样式和交互效果
class CommonButton extends StatelessWidget {
  /// 按钮文本
  final String text;

  /// 点击回调
  final VoidCallback? onPressed;

  /// 按钮类型
  final ButtonType type;

  /// 按钮大小
  final ButtonSize size;

  /// 是否加载中
  final bool isLoading;

  /// 是否禁用
  final bool isDisabled;

  /// 自定义宽度
  final double? width;

  /// 自定义高度
  final double? height;

  /// 图标
  final IconData? icon;

  /// 图标位置
  final IconPosition iconPosition;

  /// 背景颜色
  final Color? backgroundColor;

  /// 自定义颜色
  final Color? customColor;

  /// 边框半径
  final double? borderRadius;

  /// 边框宽度
  final double? borderWidth;

  /// 边框颜色
  final Color? borderColor;

  /// 文本样式
  final TextStyle? textStyle;

  /// 内边距
  final EdgeInsetsGeometry? padding;

  /// 外边距
  final EdgeInsetsGeometry? margin;

  /// 阴影
  final List<BoxShadow>? boxShadow;

  /// 渐变色
  final Gradient? gradient;

  final Color? color;

  const CommonButton({
    super.key,
    required this.text,
    this.onPressed,
    this.type = ButtonType.primary,
    this.size = ButtonSize.medium,
    this.isLoading = false,
    this.isDisabled = false,
    this.width,
    this.height,
    this.icon,
    this.iconPosition = IconPosition.left,
    this.backgroundColor,
    this.customColor,
    this.borderRadius,
    this.borderWidth,
    this.borderColor,
    this.textStyle,
    this.padding,
    this.margin,
    this.boxShadow,
    this.gradient,
    this.color,
  });

  @override
  Widget build(BuildContext context) {
    final themeManager = ThemeManager.instance;

    // 计算按钮尺寸
    final buttonSize = _getButtonSize();

    // 计算按钮颜色
    final buttonColors = _getButtonColors(themeManager);

    // 计算文本样式
    TextStyle? finalTextStyle = _getTextStyle(buttonColors['textColor']!);
    if (color != null) {
      finalTextStyle = finalTextStyle.copyWith(color: color);
    }
    // 是否可点击
    final isClickable = !isDisabled && !isLoading && onPressed != null;

    Widget buttonChild = _buildButtonContent(finalTextStyle);

    return Container(
      width: width ?? buttonSize.width,
      height: height ?? buttonSize.height,
      margin: margin,
      child: Material(
        color: backgroundColor ?? Colors.transparent,
        child: InkWell(
          onTap: isClickable ? onPressed : null,
          borderRadius: BorderRadius.circular(borderRadius ?? 8.0),
          child: Container(
            padding: padding ?? buttonSize.padding,
            decoration: BoxDecoration(
              color: gradient == null ? buttonColors['backgroundColor'] : null,
              gradient: gradient,
              borderRadius: BorderRadius.circular(borderRadius ?? 8.0),
              border: borderWidth != null && borderWidth! > 0
                  ? Border.all(
                      color: borderColor ?? buttonColors['borderColor']!,
                      width: borderWidth!,
                    )
                  : type == ButtonType.outline
                      ? Border.all(
                          color: borderColor ?? buttonColors['borderColor']!,
                          width: 1.0,
                        )
                      : null,
              boxShadow: boxShadow ??
                  (type == ButtonType.primary && !isDisabled
                      ? [
                          BoxShadow(
                            color: (customColor ?? themeManager.primaryColor)
                                .withOpacity(0.3),
                            blurRadius: 8.0,
                            offset: const Offset(0, 2),
                          ),
                        ]
                      : null),
            ),
            child: buttonChild,
          ),
        ),
      ),
    );
  }

  /// 构建按钮内容
  Widget _buildButtonContent(TextStyle textStyle) {
    if (isLoading) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: [
          SizedBox(
            width: 16,
            height: 16,
            child: CircularProgressIndicator(
              strokeWidth: 2,
              valueColor: AlwaysStoppedAnimation<Color>(textStyle.color!),
            ),
          ),
          const SizedBox(width: 8),
          Text('加载中...', style: textStyle),
        ],
      );
    }

    if (icon != null) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.center,
        mainAxisSize: MainAxisSize.min,
        children: iconPosition == IconPosition.left
            ? [
                Icon(icon, color: textStyle.color, size: _getIconSize()),
                const SizedBox(width: 8),
                Text(text, style: textStyle),
              ]
            : [
                Text(text, style: textStyle),
                const SizedBox(width: 8),
                Icon(icon, color: textStyle.color, size: _getIconSize()),
              ],
      );
    }

    return Text(
      text,
      style: textStyle,
      textAlign: TextAlign.center,
    );
  }

  /// 获取按钮尺寸
  _ButtonSize _getButtonSize() {
    switch (size) {
      case ButtonSize.small:
        return _ButtonSize(
          width: 80,
          height: 32,
          padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
        );
      case ButtonSize.medium:
        return _ButtonSize(
          width: 120,
          height: 40,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        );
      case ButtonSize.large:
        return _ButtonSize(
          width: 160,
          height: 48,
          padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
        );
      case ButtonSize.extraLarge:
        return _ButtonSize(
          width: 200,
          height: 56,
          padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 16),
        );
    }
  }

  /// 获取按钮颜色
  Map<String, Color> _getButtonColors(ThemeManager themeManager) {
    final primaryColor = customColor ?? themeManager.primaryColor;
    final isDark = themeManager.isDarkMode;

    if (isDisabled) {
      return {
        'backgroundColor': isDark ? Colors.grey[800]! : Colors.grey[300]!,
        'textColor': isDark ? Colors.grey[600]! : Colors.grey[500]!,
        'borderColor': isDark ? Colors.grey[700]! : Colors.grey[400]!,
      };
    }

    switch (type) {
      case ButtonType.primary:
        return {
          'backgroundColor': primaryColor,
          'textColor': Colors.white,
          'borderColor': primaryColor,
        };
      case ButtonType.secondary:
        return {
          'backgroundColor': isDark ? Colors.grey[700]! : Colors.grey[200]!,
          'textColor': isDark ? Colors.white : Colors.black87,
          'borderColor': isDark ? Colors.grey[600]! : Colors.grey[300]!,
        };
      case ButtonType.outline:
        return {
          'backgroundColor': Colors.transparent,
          'textColor': primaryColor,
          'borderColor': primaryColor,
        };
      case ButtonType.text:
        return {
          'backgroundColor': Colors.transparent,
          'textColor': primaryColor,
          'borderColor': Colors.transparent,
        };
      case ButtonType.danger:
        return {
          'backgroundColor': Colors.red,
          'textColor': Colors.white,
          'borderColor': Colors.red,
        };
      case ButtonType.success:
        return {
          'backgroundColor': Colors.green,
          'textColor': Colors.white,
          'borderColor': Colors.green,
        };
      case ButtonType.warning:
        return {
          'backgroundColor': Colors.orange,
          'textColor': Colors.white,
          'borderColor': Colors.orange,
        };
    }
  }

  /// 获取文本样式
  TextStyle _getTextStyle(Color textColor) {
    final baseStyle = TextStyle(
      color: textColor,
      fontSize: _getFontSize(),
      fontWeight:
          type == ButtonType.primary ? FontWeight.w600 : FontWeight.w500,
    );

    return textStyle?.copyWith(
          color: textStyle?.color ?? textColor,
        ) ??
        baseStyle;
  }

  /// 获取字体大小
  double _getFontSize() {
    switch (size) {
      case ButtonSize.small:
        return 12;
      case ButtonSize.medium:
        return 14;
      case ButtonSize.large:
        return 16;
      case ButtonSize.extraLarge:
        return 18;
    }
  }

  /// 获取图标大小
  double _getIconSize() {
    switch (size) {
      case ButtonSize.small:
        return 14;
      case ButtonSize.medium:
        return 16;
      case ButtonSize.large:
        return 18;
      case ButtonSize.extraLarge:
        return 20;
    }
  }
}

/// 按钮类型
enum ButtonType {
  primary,
  secondary,
  outline,
  text,
  danger,
  success,
  warning,
}

/// 按钮大小
enum ButtonSize {
  small,
  medium,
  large,
  extraLarge,
}

/// 图标位置
enum IconPosition {
  left,
  right,
}

/// 按钮尺寸数据
class _ButtonSize {
  final double width;
  final double height;
  final EdgeInsetsGeometry padding;

  _ButtonSize({
    required this.width,
    required this.height,
    required this.padding,
  });
}
